//! HTTP处理器

use std::sync::Arc;
use axum::{
    extract::State,
    response::Json,
    http::StatusCode,
};
use serde::{Deserialize, Serialize};
use data_gateway_kernel::{DataGatewayKernel, Query, QueryType};
use data_gateway_kernel::query::{QueryOptions, QueryContext};
use serde_json::json;

/// 查询请求
#[derive(Debug, Deserialize)]
pub struct QueryRequest {
    /// 查询类型
    pub query_type: String,
    /// 查询内容
    pub query: String,
    /// 查询参数
    pub params: Option<serde_json::Value>,
}

/// 查询响应
#[derive(Debug, Serialize)]
pub struct QueryResponse {
    /// 是否成功
    pub success: bool,
    /// 响应数据
    pub data: Option<serde_json::Value>,
    /// 错误信息
    pub error: Option<String>,
    /// 查询统计
    pub stats: Option<serde_json::Value>,
}

/// 健康检查处理器
pub async fn health_handler() -> Json<serde_json::Value> {
    Json(json!({
        "status": "healthy",
        "timestamp": chrono::Utc::now().to_rfc3339()
    }))
}

/// 状态查询处理器
pub async fn status_handler(
    State(kernel): State<Arc<DataGatewayKernel>>,
) -> Result<Json<serde_json::Value>, StatusCode> {
    match kernel.get_stats().await {
        Ok(stats) => Ok(Json(json!({
            "status": "running",
            "stats": stats,
            "timestamp": chrono::Utc::now().to_rfc3339()
        }))),
        Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
    }
}

/// 查询处理器
pub async fn query_handler(
    State(kernel): State<Arc<DataGatewayKernel>>,
    Json(request): Json<QueryRequest>,
) -> Result<Json<QueryResponse>, StatusCode> {
    // 解析查询类型
    let query_type = match request.query_type.as_str() {
        "sql" => QueryType::Sql,
        "graphql" => QueryType::GraphQL,
        "rest" => QueryType::Rest,
        "flight_sql" => QueryType::FlightSql,
        "script" => QueryType::Script,
        _ => QueryType::Sql, // 默认为SQL
    };

    // 创建查询对象
    let query = Query {
        id: uuid::Uuid::new_v4().to_string(),
        query_type,
        content: request.query,
        parameters: std::collections::HashMap::new(), // 简化处理
        options: QueryOptions::default(),
        context: QueryContext::default(),
    };

    // 执行查询 - 使用正确的方法名
    match kernel.handle_query(query).await {
        Ok(result) => {
            let response = QueryResponse {
                success: true,
                data: Some(json!({
                    "result_type": "success",
                    "message": "查询执行成功",
                    "rows_affected": 0
                })),
                error: None,
                stats: Some(json!({
                    "duration_ms": result.stats.duration_ms,
                    "rows_processed": result.stats.rows_processed
                })),
            };
            Ok(Json(response))
        }
        Err(e) => {
            let response = QueryResponse {
                success: false,
                data: None,
                error: Some(e.to_string()),
                stats: None,
            };
            Ok(Json(response))
        }
    }
}
